package web.controller;

import config.SpringContextUtil;
import entity.User;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Dispatcher;
import service.UserService;
import serviceImpl.UserServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "user_setting",urlPatterns = "/user/setting")
public class UserServlet extends HttpServlet {
    private final String user_setting_page ="/WEB-INF/views/user/user_setting.jsp";
    private final String login_page = "/WEB-INF/views/login.jsp";
    @Autowired
    private UserService userService;
    @Override
    public void init() throws ServletException {
        this.userService = (UserServiceImpl) SpringContextUtil.getBean("userServiceImpl", UserServiceImpl.class);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        //session保存的userID
        User user_1 = (User) req.getSession().getAttribute("user");

        //表单输入的数据
        User user = new User();
        user.setUserID(user_1.getUserID());
        user.setFullname(req.getParameter("fullname"));
        user.setPassword(req.getParameter("password"));
        user.setTelephone(req.getParameter("telephone"));
        if (action == null){
            RequestDispatcher dispatcher = req.getRequestDispatcher(user_setting_page);
            dispatcher.forward(req,resp);
        } else if (action.equals("edit")) {
            userService.updateUser(user);
            req.getSession().invalidate();
            resp.setContentType("text/html");
            PrintWriter out = resp.getWriter();
            out.println("<script type=\"text/javascript\">");
            out.println("window.top.location.href='http://localhost:8080/';");
            out.println("</script>");

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

}
